﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;
using Orchard;
using System.Web.Hosting;
using Orchard.Localization;
using Orchard.Environment.Extensions;
using Orchard.ContentManagement;
using RaisingStudio.Razor.Models;
using RazorEngine.Templating;
using System.Text;
using Orchard.Logging;

namespace RaisingStudio.Razor.Services
{
    public class RazorService : IRazorService
    {
        public Localizer T { get; private set; }
        public ILogger Logger { get; set; }

        public RazorService()
        {
            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
        }

        public string Run(string template, IRazorModel razorModel)
        {
            string content = string.Empty;
            if (!string.IsNullOrWhiteSpace(template))
            {
                try
                {
                    content = RazorEngine.Razor.Parse(template, razorModel);
                }
                catch (TemplateCompilationException tcex)
                {
                    StringBuilder errorStringBuilder = new StringBuilder();
                    errorStringBuilder.AppendLine(tcex.Message);
                    errorStringBuilder.AppendLine(string.Format("Errors ({0}):", tcex.Errors.Count));
                    foreach (var error in tcex.Errors)
                    {
                        errorStringBuilder.AppendLine(error.ToString());
                    }
                    content = errorStringBuilder.ToString();
                }
                catch (Exception ex)
                {
                    content = ex.ToString();
                    Debug.WriteLine(ex);
                    Logger.Error(ex, "An error occurred while run razor engine.");
                }
            }
            return content;
        }

        public string Run(string template, IOrchardServices services, dynamic content, dynamic context)
        {
            RazorModel razorModel = new RazorModel(services, T, content, context);
            return Run(template, razorModel);
        }


        public string Run(string template, IOrchardServices services, dynamic content)
        {
            return Run(template, services, content, null);
        }

        public string Run(string template, IOrchardServices services)
        {
            return Run(template, services, null, null);
        }
    }
}